package cn.edu.abtu.service.impl;

import cn.edu.abtu.service.OssService;
import cn.edu.abtu.utils.ConstantPropertiesUtils;
import cn.edu.abtu.vo.ResponseData;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public ResponseData uploadFileAvatar(MultipartFile file) {
        try {
            String endpoint = ConstantPropertiesUtils.EDN_POINT;
            String keyId = ConstantPropertiesUtils.KEY_ID;
            String keySecret = ConstantPropertiesUtils.KEY_SECRET;
            String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
            //创建OSS实列
            OSS ossClient = new OSSClientBuilder().build(endpoint,keyId,keySecret);
            //获取上传输入流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String str = fileName.substring(fileName.lastIndexOf("."));
            String originalFilename = uuid+str;
            //第一个参数: BUCKET_NAME
            //第二个参数: 上传到oss文件和文件名称
            //第三个参数: 上传文件输入流
            String datePath = new DateTime().toString("yyyy/MM/dd");
            originalFilename = datePath + "/" + originalFilename;
            ossClient.putObject(bucketName,originalFilename,inputStream);
            ossClient.shutdown();
            //把上传之后的文件路径进行返回   https://guli-20191446.oss-cn-hangzhou.aliyuncs.com/headbg.gif
            String url = "https://"+bucketName+"."+endpoint+"/"+originalFilename;
            return ResponseData.success("上传成功",url);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail();
        }
    }
}
